#! /usr/bin/env python

import os.path
import re
import sys

eps_label_re = re.compile('Year Ending (Dec|Mar)-13\s+[0-9]+\s+')
ltg_label_re = re.compile('LT Growth Rate \(%\)\s+([0-9]+)\s+')
blank_re = re.compile('\s+')

def parse(financials, line):
    if line.endswith('INR'):
        financials['pri'] = float(line.strip().split('I')[0].replace(',', ''))
    elif (line.startswith('Year Ending Mar-13') or
          line.startswith('Year Ending Dec-13')):
        financials['eps'] = float(blank_re.split(
                eps_label_re.sub('', line), 1)[0].replace(',', ''))
    elif line.startswith('LT Growth Rate (%)'):
        match = ltg_label_re.search(line)
        financials['num'] = int(match.group(1))
        financials['ltg'] = float(blank_re.split(
                ltg_label_re.sub('', line), 1)[0].replace(',', ''))
    elif '.NS on National Stock Exchange of India' in line:
        financials['sym_reu'] = line.split(' ', 1)[0]

def process(financials):
    try:
        pri = financials['pri']
        eps = financials['eps']
        ltg = financials['ltg']
        sym_nse = financials['sym_nse']
        sym_reu = financials['sym_reu']
        num = financials['num']
        if num < 3:
            return
        val = eps * (8.5 + 2 * ltg) * 4.4 / 8.56
        print ('{sym_nse}\t{sym_reu}\t{num}\t{pri}\t{val:0.2f}\t'
               '{diff:0.2f}%\t{verdict}'.format(
                sym_nse=sym_nse, sym_reu=sym_reu, num=num, pri=pri, val=val,
                diff=(val - pri) / pri * 100, verdict='YES'
                if val > pri else 'NO'))
    except KeyError as err:
        print >>sys.stderr, financials['sym_nse'], err

def main():
    """Main function"""
    file_seq = sys.argv[1:]
    for cur_file in file_seq:
        with open(cur_file, 'r') as in_file:
            data = in_file.read()
        if 'LT Growth Rate' not in data:
            continue
        financials = {'sym_nse': os.path.splitext(os.path.basename(cur_file))[0]}
        line_seq = data.split('\n')
        for cur_line in line_seq:
            if 'ltg' in financials:
                break
            parse(financials, cur_line.strip())
        process(financials)

if __name__ == '__main__':
    main()
